package com.ruoyi.game.websocket.notify;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.game.websocket.handler.GameWebSocketHandler;
import com.ruoyi.game.websocket.message.packet.WsPacket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
@Component
@RequiredArgsConstructor
public class GameRoomNotifier {

    private final GameWebSocketHandler handler;
    private final ObjectMapper mapper;

    /** 发送数据给某个玩家 */
    public void sendToPlayer(WebSocketSession session, WsPacket<?> packet) {
        if (session == null || !session.isOpen()) return;
        try {
            String json = mapper.writeValueAsString(packet);
            session.sendMessage(new TextMessage(json));
        } catch (Exception e) {
            log.error("[Notifier] 发送消息失败：{}", e.getMessage(), e);
        }
    }

    /** 向指定房间广播（包括自己） */
    public void broadcastToRoom(Long roomId, WsPacket<?> packet) {
        handler.broadcastPacketToRoom(roomId, packet);
    }

    /** 向房间广播，排除某玩家 */
    public void broadcastExclude(Long roomId, WsPacket<?> packet, Long excludePlayerId) {
        handler.broadcastExclude(roomId, packet, excludePlayerId);
    }

    /** 错误消息发送 */
    public void sendError(WebSocketSession session, int code, String msg) {
        sendToPlayer(session, com.ruoyi.game.websocket.message.packet.WsPackets.error(code, msg));
    }

    /** PONG 响应 */
    public void sendPong(WebSocketSession session) {
        sendToPlayer(session, com.ruoyi.game.websocket.message.packet.WsPackets.pong(System.currentTimeMillis()));
    }
}
